package no.hib.tod141.hasj.taghandelers;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class CopyrightTag extends SimpleTagSupport {

        private int since = Calendar.getInstance().get(Calendar.YEAR);
       
        public void doTag() throws JspException, IOException {
                String copyright = "© ";
               
                copyright += convertToRoman(since);
               
                copyright += " - ";
               
                copyright += convertToRoman(Calendar.getInstance().get(Calendar.YEAR));
               
                copyright += " - ";
               
                StringWriter sw = new StringWriter();
                getJspBody().invoke(sw);
                copyright += sw;
               
                JspWriter out = getJspContext().getOut();
                out.println(copyright);
        }
       
        public void setSince(int since) {
                this.since = since;
        }
       
        public String convertToRoman(int binary) {
                //kode for denne metoden tatt fra http://www.roseindia.net/java/java-tips/45examples/misc/roman/roman.shtml
               
            // Parallel arrays used in the conversion process.
            final String[] RCODE = {"M", "CM", "D", "CD", "C", "XC", "L",
                                                   "XL", "X", "IX", "V", "IV", "I"};
            final int[]    BVAL  = {1000, 900, 500, 400,  100,   90,  50,
                                                   40,   10,    9,   5,   4,    1};
           
            //=========================================================== binaryToRoman
        if (binary <= 0 || binary >= 4000) {
            throw new NumberFormatException("Value outside roman numeral range.");
        }
        String roman = "";         // Roman notation will be accumualated here.
               
        // Loop from biggest value to smallest, successively subtracting,
        // from the binary value while adding to the roman representation.
        for (int i = 0; i < RCODE.length; i++) {
            while (binary >= BVAL[i]) {
                binary -= BVAL[i];
                roman  += RCODE[i];
            }
            }  
        return roman;
        }
}